<style>
  .collection_top_bar{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 44px 0 20px 0;
  }
  .collection_top_bar .product_num{
    font-weight: 500;
  }
	.product-list-warp{
		overflow: hidden;
	}

	.product-list-warp ul{
		display: grid;
    grid-row-gap: 30px;
    grid-column-gap: 40px;
    grid-template-columns: repeat(var(--web_column), minmax(50px, 1fr));
	}


  .product-list-warp li {
    list-style-type: none;
    text-align: center;
  }

  .product-list-warp .product_pic {
    margin-bottom: 30px;
    position: relative;
  }

  .product-list-warp .soldout {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 30px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    line-height: 50px;
    background: rgba(0, 0, 0, 0.3);
    color: #fff;
    font-size: 14px;
  }

  .product-list-warp .product_pic .product_img {
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    width: 100%;
  }

  .product-list-warp .product_pic img {
    max-width: 100%;
  }

  .product-list-warp .block_product_name {
    margin-bottom: 10px;
    line-height: 1.5;
  }

  .product-list-warp .product_price {
    font-weight: bold;
  }

  .product-list-warp .product_oldprice {
    color: #888;
    text-decoration: line-through;
    margin-left: 5px;
    font-weight: normal;
  }


  @media (max-width: 767px) {
    .product-list-warp ul {
      grid-row-gap: 30px;
      grid-column-gap: 15px;
      grid-template-columns: repeat(2, minmax(50px, 1fr)) !important;
    }
    .product-list-warp .collection_content_more {
      margin-top: 30px;
    }
    .product-list-warp .product_pic {
      margin-bottom: 20px;
    }
  }


</style>





<style>
  .mo-pagination {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 40px 0;
      font-size: 0;
  }
  .mo-pagination .mo-pagination-value, .mo-pagination .mo-pagination-handle {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      box-sizing: border-box;
      margin: 0 5px;
  }

  .mo-pagination .mo-pagination-handle {
      overflow: hidden;
      cursor: pointer;
  }
  .mo-pagination .mo-pagination-handle path {
      fill:#1D1F21
  }

  .mo-pagination .mo-pagination-value {
      color: #1D1F21;
  }
  .mo-pagination .mo-pagination-value:hover{
      border: 1px solid #1D1F21;
  }
  .mo-pagination .mo-pagination-value-active{
      color: #1D1F21;
      border: 1px solid #1D1F21;
  }
  .mo-pagination .mo-pagination-handle-disable{
      cursor: not-allowed;
  }
  .mo-pagination .mo-pagination-handle-disable path{
      fill:#999999
  }
  .filter-price-box{
    display: flex;
  }
  .filter-price-box span{
    max-width: 40px;
    margin-right:6px;
  }
  .filter-price-box input{
    padding: 9px;
    flex: 1;
    flex-shrink: 0;
    border: 1px solid rgba(136, 138, 139, 0.2);
    border-radius: 4px;
  }
</style>


<style>
  .promotion_detail_nav{
    width:100%;
    background:  var(--banner_side_color);
  }
  .promotion_detail_nav_warp{
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 15px 20px;
    justify-content: space-between;
    background: linear-gradient(90deg, var(--banner_color-l) 0%, var(--banner_color-r) 100%);
    color: var(--text_color);

  }
  
  .promotion_detail_container_wrapper{
    width: 100%;
    max-width: var(--general_layout_width);
    margin: 0 auto;
  }
  
  .moi-countdow-time{
    display: flex;
  flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    gap: 10px;
  }
  .moi-countdow-time>div{
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .moi-countdow-time-label{
    color: var(--text_color);
    text-align: center;
  }
  .moi-countdow-time-value{
    min-width: 40px;
    height: 26px;
    background: var(--countdown_bg_color);
    opacity: 1;
    color: var(--countdown_text_color);
    border-radius: 4px 4px 4px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
  }
 


  .z-text-roll {
    
    white-space: nowrap;
    overflow: hidden;
    position: relative;
    flex: 1;
    max-width: 100%;
    font-size:16px;
}
.z-text-roll>span {
    position: relative;
    display: inline-block;
}

.block_title{
		margin-top: calc(var(--general_layout_spacing) * var(--title_margin_bottom_scale));
	}

.z-is-roll>span {

  margin-right: 10px;
  animation: z-text-anim 30s linear infinite;
}
.moi-countdow-time{
      margin-left: 20px;
    }
@keyframes z-text-anim {
    0% {
        transform: translateX(0);
    }
    100% {
        transform: translateX(calc(-100% - 20px));
    }
}
@media (max-width: 767px) {
    .promotion_detail_nav_warp{
      flex-direction: column;
      align-items: center;
      padding: 15px;
      gap: 15px;
      box-sizing: border-box;

    }
    .z-is-roll{
      margin-right: 0;
    }
    .moi-countdow-time{
      margin-left: 0;
    }
  }
  </style>


{% if section.params %}
{% assign promotion = section.params.promotion %}
{% assign promotion_view_config = section.params.promotion_view_config %}
{% assign sort_options = section.params.sort_options %}
{% endif %}

<div class="container_wrapper">
  {% include 'block_title', title:promotion.promotion_name %}
</div>

<div class="promotion_detail_nav" style="--banner_color-l:{{promotion_view_config.banner_color1}};--banner_side_color:{{promotion_view_config.side_banner_color}};--banner_color-r:{{promotion_view_config.banner_color2}};--text_color:{{promotion_view_config.text_color}};--countdown_bg_color:{{promotion_view_config.countdown_bg_color}};--countdown_text_color:{{promotion_view_config.countdown_text_color}};">
	<div class="promotion_detail_container_wrapper">
		<div class="promotion_detail_nav_warp">
			<div class="promotion_detail_tips z-text-roll" id="promotion_detail_tips"></div>
			<div class="moi-countdow-time" id="countdow-warp"></div>
		</div>
	</div>
</div>


<div class="container_wrapper ">
	<div class="collection_top_bar">
		<div class="product_num"><span></span> {{ lang.collections.detail.products }}</div>
		<div class="" style="display: flex;align-items: center;gap:15px">
			{% if section.settings.show_sort %}
			<span>{{ lang.general.sort_by }}</span>
			<select class="form-control" id='sort_by_select'>
				{% for option in sort_options %}
				<option value="{{option.value}}" {% if option.value == sort_by %}selected="selected" {% endif %}>{{ option.name }}</option>
				{% endfor %}
			</select>
			{% endif %}

		</div>
	</div>
</div>

<div class="container_wrapper block_collection_waterfall " style="--web_column:{{section.settings.web_column | default:4}}">
	<div id="collection-product-warp" style='min-height:300px'>
		
	</div>

</div>

{% include 'collection_product_waterfall' %}
<script type="text/html" id="collection-paginate-temp">
  {% raw %}
    {% if paginate and paginate.current_page != 0 %}
      <div class="mo-pagination">
          <a href="javascript:;" data-page="{{paginate.previous.page}}" class="mo-pagination-handle {% if paginate.current_page == 1 %}mo-pagination-handle-disable{% endif %}">
              <svg t="1632633670584" class="arrow-1" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1448" width="16" height="16">
                  <path d="M751.61600001 175.104l-360.0896 337.6128 359.67999999 336.0768a50.3296 50.3296 0 0 1 0 74.3936 58.88 58.88 0 0 1-79.4112 0.1024l-399.36-373.248a50.3296 50.3296 0 0 1 0-74.3424l399.7184-374.8864a58.88 58.88 0 0 1 79.4112-0.1024 50.3296 50.3296 0 0 1 0 74.3936z" p-id="1449" fill="#888888"></path>
              </svg>
          </a>
          {% for part in paginate.parts %}
          {% if part.is_link %}
          <a href="javascript:;" data-page="{{part.page}}" class="mo-pagination-value {% if part.title == paginate.current_page %}mo-pagination-value-active{% endif %}">{{ part.title }}</a>
          {% else %}
          <span class="mo-pagination-value">{{ part.title }}</span>
          {% endif %}
          {% endfor %}
          <a href="javascript:;" data-page="{{paginate.next.page}}"  class="mo-pagination-handle {% if paginate.current_page == paginate.pages %}mo-pagination-handle-disable{% endif %}">
              <svg t="1632633684430" class="arrow-1" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1590" width="16" height="16">
                  <path d="M272.384 848.896l360.0896-337.6128-359.68-336.0768a50.3296 50.3296 0 0 1 0-74.3936 58.88 58.88 0 0 1 79.4112-0.1024l399.36 373.248a50.3296 50.3296 0 0 1 0 74.3424l-399.7184 374.8864a58.88 58.88 0 0 1-79.4112 0.1024 50.3296 50.3296 0 0 1 0-74.3936z" p-id="1591" fill="#888888"></path>
              </svg>
          </a>
      </div>
    {% endif %}
  {% endraw %} 
</script>
<script type="text/html" id="collection-product-empty-temp">
  {% include "empty" , text:lang.general.empty  %}
</script>
<script>
	$(function(){

    var promotion = {{promotion|json}};
    var promotionConfig = {{promotion_view_config|json}};
		function getParam(page){
			return {
				page:page || 1,
				page_size:'{{section.settings.pagesize}}',
				sort_by:$('#sort_by_select').val() || "",
			}
		}

    {% comment %} {
      "title": "Promotions",
      "title_item": "Promotion",
      "starts_at": "Sales starts in",
      "ends_at": "Sales ends in",
      "ended": "Sales ended",
      "day": "Day",
      "discount_rule_1": "Buy {rule_condition} get {rule_discount} OFF",
      "discount_rule_2": "Add {condition} to get {next_discount} OFF",
      "discount_rule_3": "Got {finish_discount} OFF already! Add {condition} to get {next_discount} OFF",
      "discount_rule_4": "Congratulations! You've got {finish_discount} OFF, checkout now!",
      "discount_rule_5": "Save {rule_discount} for Every {rule_condition} Spent",
      "discount_rule_6": "{rule_discount} OFF FOR {rule_condition} item",
      "discount_rule_7": "Add {condition} to get {next_discount} OFF of the {next_condition} item",
      "discount_rule_8": "Got {finish_discount} OFF already! Add {condition} to get {next_discount} OFF of the {next_condition} item",
      "discount_rule_9": "Buy {rule_condition} for {rule_discount}",
      "discount_rule_10": "Add {condition}  to enjoy bundle price {next_discount}  on {next_condition}",
      "discount_rule_11": "You've received bundle price {finish_discount} on {finish_condition}! Add {condition}  to enjoy bundle price {next_discount}  on {next_condition}",
      "discount_rule_12": "Congratulations! You've received bundle price {finish_discount} on {finish_condition}, checkout now!",
      "piece": "items"
  } {% endcomment %}

    function discountToFloorTip(){
      var discount_rule_1 = `{{lang.promotions.discount_rule_1}}`; 
      var discount_rule_2 = `{{lang.promotions.discount_rule_2}}`; 
      var discount_rule_3 = `{{lang.promotions.discount_rule_3}}`; 
      var discount_rule_4 = `{{lang.promotions.discount_rule_4}}`; 
      var discount_rule_5 = `{{lang.promotions.discount_rule_5}}`; 
      var discount_rule_6 = `{{lang.promotions.discount_rule_6}}`; 
      var discount_rule_7 = `{{lang.promotions.discount_rule_7}}`; 
      var discount_rule_8 = `{{lang.promotions.discount_rule_8}}`; 
      var discount_rule_9 = `{{lang.promotions.discount_rule_9}}`; 
      var discount_rule_10 = `{{lang.promotions.discount_rule_10}}`; 
      var discount_rule_11 = `{{lang.promotions.discount_rule_11}}`; 
      var discount_rule_12 = `{{lang.promotions.discount_rule_12}}`; 
      return {
        rule_not_tip_1: discount_rule_6.replace(/{rule_discount}/g,'{value}').replace(/{rule_condition}/g,'{ordinalLabel}'),
        rule_not_tip_2:discount_rule_1.replace(/{rule_condition}/g,'{label}').replace(/{rule_discount}/g,'{value}'),
        rule_not_tip_3:discount_rule_5.replace(/{rule_discount}/g,'{value}').replace(/{rule_condition}/g,'{label}'),
        rule_not_tip_4:discount_rule_9.replace(/{rule_condition}/g,'{label}').replace(/{rule_discount}/g,'{value}'),

        rule_dasics_tip_1:discount_rule_2.replace(/{condition}/g,'{diffLabel}').replace(/{next_discount}/g,'{nextValue}'),
        rule_dasics_tip_2:discount_rule_7.replace(/{condition}/g,'{diffLabel}').replace(/{next_discount}/g,'{nextValue}').replace(/{next_condition}/g,'{nextOrdinalLabel}') ,
        rule_dasics_tip_3:discount_rule_10.replace(/{condition}/g,'{diffLabel}').replace(/{next_discount}/g,'{nextValue}').replace(/{next_condition}/g,'{nextLable}'),
        
        rule_middle_tip_1:discount_rule_3.replace(/{condition}/g,'{diffLabel}').replace(/{finish_discount}/g,'{value}').replace(/{next_discount}/g,'{nextValue}') ,
        rule_middle_tip_2:discount_rule_8.replace(/{condition}/g,'{diffLabel}').replace(/{finish_discount}/g,'{foldValue}').replace(/{next_discount}/g,'{nextValue}').replace(/{next_condition}/g,'{nextOrdinalLabel}'),
        rule_middle_tip_3:discount_rule_11.replace(/{condition}/g,'{diffLabel}').replace(/{finish_discount}/g,'{currentValue}').replace(/{finish_condition}/g,'{currentLable}').replace(/{next_discount}/g,'{nextValue}').replace(/{next_condition}/g,'{nextLable}'),

        rule_top_tip_1:discount_rule_4.replace(/{finish_discount}/g,'{value}'),
        rule_top_tip_2:discount_rule_12.replace(/{finish_discount}/g,'{topValue}').replace(/{finish_condition}/g,'{topLabel}'),
      }
    }

    const tipsObject = discountToFloorTip();
    


    function ruleFloor(rule_param, products,currentPromotion) {
      let rules = rule_param.rule.filter(item => parseFloat(item.value) > 0)
  
  
  
  
      // 英文序数词缩写后缀
      function ordinalNumber(n) {
        return n + (['st', 'nd', 'rd'][n < 20 ? n - 1 : n % 10 - 1] || 'th')
      }
  
      // 过滤满足条件的   type优惠类型
      function formatValue(value, type) {
        if ([2, 4, 5].includes(type)) {
          return value + '%';
        }
        return formatMoney(value,oemcart_currency)
      }
  
  
      // 过滤条件  type优惠类型
      function formatLabel(value, type) {
        if ([2 ,3, 5, 6].includes(type)) {
          return value + "{{lang.promotions.piece}}";
        }
        return formatMoney(value,oemcart_currency)
      }
  
      // 获取对比值是数量还是价格
      function toValue() {
        if ([1, 4].includes(rule_param.type)) {
          const price = products.reduce(function (prev, item) {
            return prev + item.original_line_price
          }, 0)
          return price.toFixed(2);
        }
  
        return products.reduce(function (prev, item) {
          return prev + item.quantity
        }, 0)
      }
  
  
      function getSingleProductList() {
        const newProduct = [];
        products.forEach(function (item) {
          for (let i = 0; i < item.quantity; i++) {
            newProduct.push({
              price: item.price
            })
          }
        })
        return newProduct
      }
  
  
  
      //获取当前在第几成
      function getFloorIndex(value) {
  
        for (let i = rules.length - 1; i >= 0; i--) {
          if (parseFloat(value) >= parseFloat(rules[i].ge)) {
            return i
          }
        }
        return -1
      }
  
      //一层不满足
      function notFloorTips() {
        switch (Number(rule_param.type)) {
          case 5:
            return tipsObject.rule_dasics_tip_2//`Add {diffLabel} to get {nextValue} OFF of the {nextOrdinalLabel} item`;
          case 6:
            return tipsObject.rule_dasics_tip_3//`Add {diffLabel} to enjoy bundle price {nextValue} on {nextLable}`;
          default:
            return tipsObject.rule_dasics_tip_1// `Add {diffLabel} to get {nextValue} OFF`;
        }
      }
  
      //满足某一层
      function arrivalFloorTips() {
        const basicsText = tipsObject.rule_middle_tip_1// `Got {value} OFF already! Add {diffLabel} to get {nextValue} OFF`;

        switch (Number(rule_param.type)) {
          case 3:
            return basicsText.replace(/{value}/g,'{foldValue}')// `Got {foldValue} OFF already! Add {diffLabel} to get {nextValue} OFF`;
          case 5:
            return  tipsObject.rule_middle_tip_2//`Got {foldValue} OFF already! Add {diffLabel} to get {nextValue} OFF of the {nextOrdinalLabel} item`;
          case 6:
            return  tipsObject.rule_middle_tip_3//`You've received bundle price {currentValue} on {currentLable}! Add {diffLabel}  to enjoy bundle price {nextValue}  on {nextLable}`;
          default:
            return basicsText.replace(/{value}/g,'{currentValue}')// `Got {currentValue} OFF already! Add {diffLabel} to get {nextValue} OFF`;
        }
      }
  
      //最高层级
      function highestFloorTips() {
        const text = tipsObject.rule_top_tip_1// `Congratulations! You've got {value} OFF, checkout now!`;
        // `Congratulations! You've got {foldValue} OFF, checkout now!`;
        //`Congratulations! You've got {topValue} OFF, checkout now!`;
        switch (Number(rule_param.type)) {
          case 3:
          case 5:
            return text.replace(/{value}/g,'{foldValue}')
          case 6:
            return tipsObject.rule_top_tip_2// `Congratulations! You've received bundle price {topValue} on {topLabel}, checkout now!` // text.replace(/{value}/g,'{foldValue}')
          default:
            return text.replace(/{value}/g,'{topValue}') 
        }
      }
  
  
  
      // 不满足文案提示
      function notSatisfyTips() {
        let tipstr = tipsObject.rule_not_tip_4  //`Buy {label} for {value}`;
				if ([1, 2, 3, 4].includes(rule_param.type)) {
					if([1, 3].includes(rule_param.type) && rule_param.allocation_limit == 999){
						tipstr = tipsObject.rule_not_tip_3 //`Save {value} for Every {label} Spent`;
					}else{
						tipstr = tipsObject.rule_not_tip_2 //`Buy {label} get {value} OFF`;
					}
				}
				if ([5].includes(rule_param.type)) {
					tipstr = tipsObject.rule_not_tip_1 //`{value} OFF FOR {ordinalLabel} item`;
				}
				const rulesTipstr = rules.map(item => tipstr.replace(/{ordinalLabel}/g, ordinalNumber(item.ge, rule_param.type)).replace(/{label}/g, formatLabel(item.ge, rule_param.type)).replace(/{value}/g, formatValue(item.value, rule_param.type)).replace(/{ordinalValue}/g, ordinalNumber(item.value)))
				return rulesTipstr.join('&nbsp;&nbsp;')
      }
  
  
      //计算满足优惠的金额
      function computedFoldValue() {
        return  formatMoney(Math.abs(currentPromotion.discount || 0),oemcart_currency)

        const singleProductList = getSingleProductList()
        let totalPrice = 0;
        // 第X件Y折
        if (rule_param.type == 5) {
          for (let i = rules.length - 1; i >= 0; i--) {
            if (singleProductList.length >= parseFloat(rules[i].ge)) {
              let currentPrice = singleProductList[i].price;
              
              const discountedPrice =  Number(currentPrice).times(Number(rules[i].value).modulo(100))
              totalPrice += parseFloat(Number(currentPrice).minus(discountedPrice))
              if (rule_param.top_promotion == 1) {
                break;
              }
            }
          }
        }
  
        // 满件一口价类型
         if (rule_param.type == 6) {
          for (let i = rules.length - 1; i >= 0; i--) {
            if (singleProductList.length >= parseFloat(rules[i].ge)) {
              const price = singleProductList.reduce(function (prev, item, index) {
                if (index < rules[i].ge) {
                  return Number(prev).plus(item.price)
                }
                return prev
              }, 0)
              totalPrice = Number(price).minus(rules[i].value)
              break;
            }
          }
        }
        return  formatMoney(totalPrice,oemcart_currency)
      }
  
  
  
      //替换楼层规则提示  nextRule下层规则、value当前值金额或者数量、tips替换文案、type优惠券类型  reduceType 减少类型 1 金额 2折扣 
      function replaceRuleTips(props) {
        const { cuurentRule, nextRule, value, tips, type, rules } = props;
        // 距下一优惠层级的商品达标金额或件数 lable
        let diffLabel = 0;
  
        //判断是件数还是金额
        if ([1, 2].includes(type)) {
          diffLabel = (parseFloat(nextRule.ge) - parseFloat(value)).toFixed();
        } else {
          diffLabel = parseFloat(nextRule.ge) - parseFloat(value);
        }
  
        diffLabel = formatLabel(diffLabel, type)
  
        //下层的lable
        let nextLable = formatLabel(nextRule.ge, type);
  
        //当前的lable
        let currentLable = formatLabel(cuurentRule.ge, type);
  
        //当前层的value
        let currentValue = formatValue(cuurentRule.value, type);
  
        // 下一层的value
        let nextValue = formatValue(nextRule.value, type);
  
        // 下一层的序列格式value
        let nextOrdinalValue = ordinalNumber(nextRule.value);
  
        // 下一层的序列格式label
        let nextOrdinalLabel = ordinalNumber(nextRule.ge);
  
        // 顶层value
        let topValue = formatValue(rules[rules.length - 1].value,type);

        // 顶层label
        let topLabel = formatLabel(rules[rules.length - 1].ge,type);
  
        // 已经满足的条件的金额
        let foldValue = computedFoldValue();
  
  
        return tips.replace(/{diffLabel}/g, diffLabel).replace(/{nextLable}/g, nextLable).replace(/{currentLable}/g, currentLable)
          .replace(/{topValue}/g, topValue).replace(/{nextValue}/g, nextValue).replace(/{nextOrdinalLabel}/g, nextOrdinalLabel)
          .replace(/{currentValue}/g, currentValue).replace(/{nextOrdinalValue}/g, nextOrdinalValue).replace(/{foldValue}/g, foldValue).replace(/{topLabel}/g, topLabel)
  
      }
  
      const value = toValue();
  
      // 初始化不满足
      if (!value || parseFloat(value)  === 0) {
        return notSatisfyTips()
      }
  
      // 上不封顶
      if (rule_param.allocation_limit == 999 && parseFloat(value) >= parseFloat(rules[0].ge)) {
        const label = rules[0].ge;
        const val = rules[0].value;
        const maxRule = Math.floor(parseFloat(value) / parseFloat(rules[0].ge)) + 1;
        for (let i = 1; i <= maxRule; i++) {
          rules.push({
            "ge": Number(label).times(i),
            "value": Number(val).times(i)
          })
        }
      }
  
      let index = getFloorIndex(value);
      // 下一层
      let nextIndex = index + 1;
  
  
  
      //提示文章 默认满足某一层
      let tips = arrivalFloorTips();
  
  
      // 一层不满足
      if (index === -1) {
        index = 0;
        nextIndex = 0;
        tips = notFloorTips();
      }else{
       // 满足最顶层
        if (index === rules.length - 1) {
          nextIndex = rules.length - 1;
          tips = highestFloorTips();
        }
      }
  
     
      return replaceRuleTips({
        cuurentRule: rules[index],
        nextRule: rules[nextIndex],
        rules: rules,
        value: value,
        tips: tips,
        type: rule_param.type
      })
  
    }


    function initRoll(){
      let rollBox = document.querySelector('div.z-text-roll')
      let textWidth = rollBox.querySelector('span').clientWidth
      if(rollBox.clientWidth < textWidth){
          setTimeout(()=>{
            rollBox.classList.add('z-is-roll')
            $("#promotion_detail_tips").append($("#promotion_detail_tips").html())
          },3500)
      }else{
          rollBox.classList.remove('z-is-roll')
      }
    }

    moi.addEvent("miniCartChange",getCartInfoRulePromotion)

    moi.addEvent('miniCart',getCartInfoRulePromotion)

    function getCartInfoRulePromotion(){
      var miniCart = moi.getPageStorage('miniCartInfo');
      var products = [];
      if (miniCart && JSON.stringify(miniCart) != "{}") {
        var currentPromotion = miniCart.promotion.find(function(item){
          return item.id == promotion.id
        })
        if(currentPromotion){
          products = currentPromotion.possible_products;
        }
      }
      const notTipStr = ruleFloor(promotion.rule_param,products,currentPromotion);
      if(notTipStr){
        $("#promotion_detail_tips").html('<span>'+notTipStr+'</span>')
        $("#promotion_detail_tips_roll").attr('data-text',notTipStr)
        initRoll()
      }
    }

    miniCart()


    const formatNumber = (n) => {
      const s = n.toString()
      return s[1] ? s : '0' + s
    }
    function countdown(endDate, display) {
      let timer = setInterval(function() {
        let now = new Date().getTime();
        let distance = endDate - now;

        if (distance < 0) {
          clearInterval(timer);
          location.reload()
          return
        }

        let days = Math.floor(distance / (1000 * 60 * 60 * 24));
        let hours = Math.floor(distance  / (1000 * 60 * 60));
        if(promotionConfig.countdown == 1){
          hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        }
        let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        let seconds = Math.floor((distance % (1000 * 60)) / 1000);

        if(promotionConfig.countdown == 1){
          display.find("#days").text(formatNumber(days));
        }
        display.find("#hours").text(formatNumber(hours));
        display.find("#minutes").text(formatNumber(minutes));
        display.find("#seconds").text(formatNumber(seconds));
        
      }, 1000);
    }

    function countdowStatusTips(status){
      switch (status) {
        case 1:
          return '{{lang.promotions.starts_at}}'
        case 2:
          return '{{lang.promotions.ends_at}}'
        case 3:
          return '{{lang.promotions.ended}}'
      }
    }

    function showCountdowTime(){
        var ends_at = promotion.ends_at;
        var display = $("#countdow-warp");
        if(promotion.status == 2 && ends_at === -1){
            $("#promotion_detail_tips").css({"text-align": "center"})
            display.css({"display": "none"})
        }
        function appendTimeHtml(){
          if(promotionConfig.countdown == 1){
            display.html(`<span class="moi-countdow-time-label">${countdowStatusTips(promotion.status)}</span>
              <div>
                <span class="moi-countdow-time-value" id='days'></span>
                <span class="moi-countdow-time-label">{{lang.promotions.day}}</span>
                <span class="moi-countdow-time-value" id='hours'></span>
                <span class="moi-countdow-time-label">:</span>
                <span class="moi-countdow-time-value" id='minutes'></span>
                <span class="moi-countdow-time-label">:</span>
                <span class="moi-countdow-time-value" id='seconds'></span>
              </div>`);
          }else{
            display.html(`<span class="moi-countdow-time-label">${countdowStatusTips(promotion.status)}</span>
              <div>
              <span class="moi-countdow-time-value" id='hours'></span>
              <span class="moi-countdow-time-label">:</span>
              <span class="moi-countdow-time-value" id='minutes'></span>
              <span class="moi-countdow-time-label">:</span>
              <span class="moi-countdow-time-value" id='seconds'></span>
              </div>`);
          }
        }

        if(promotion.status == 1){
          appendTimeHtml()
          countdown(promotion.starts_at * 1000,display)
          return
        }

        if(promotion.status == 2){
          if(ends_at !== -1){
            appendTimeHtml()
            countdown(promotion.ends_at * 1000,display)
          }
          return
        }

        if(promotion.status == 3){
          display.html(`<span class="moi-countdow-time-label">${countdowStatusTips(promotion.status)}</span>`)
          return
        }
       
    }
    showCountdowTime()

		//请求数据
    function getCollectionProduct(params){
			var getURl = moi.setUrlParams(`/promotions/{{promotion.id}}/products`,params);
      moi.appendLoading({container:"#collection-product-warp",theme:'white',size:32})

      moi.ajax({
        url: getURl,
        type: "get",
        complete:function(){
          moi.removeLoading("#collection-product-warp")
        },
        success: function (res) {
          if (res.code !== 0) {
            return moi.message({content:res.msg,type:"error"})
          }
          var resData = res.data;
          if(resData.list.length){
            $("#collection-product-warp").html("")
            engine.parseAndRender($("#omesaas-collection-product-temp").html(), {
              products: resData.list,
              data_from: '{{data_from}}',
              lang: lang
            }).then(function(productHtml) {
              $("#collection-product-warp").append('<div class="collection_content product-list-warp"><ul>'+productHtml+'</ul></div>');
              $("#collection-product-warp").find(".product_view").click(quickview);
              $(".product_num span").text(resData.count)

							function changePaginate(paginate){
                var pageNumber = moi.isMobile()?3:5;
								var parts = [{is_link:true,title: paginate.current,page: paginate.current}]
								for(var i = 1;i<pageNumber;i++){
									var prev = paginate.current - i;
									if(prev > 0){
									
										if(i==pageNumber-1 && prev>1 ){
											parts.unshift({
												is_link: false,
												title:'...',
												page:'javascript:;'
											})
											parts.unshift({
												is_link: true,
												title:1,
												page:1
											})
										}else{
											parts.unshift({
												is_link:true,
												title: prev,
												page:prev
											})
										}
									}

									var next = paginate.current + i;
									if(next <= paginate.pageTotal){
										if(i==pageNumber-1 && next<paginate.pageTotal){
											parts.push({
												is_link: false,
												title:'...',
												page:'javascript:;'
											})
											parts.push({
												is_link: true,
												title:paginate.pageTotal,
												page:paginate.pageTotal
											})
										}else{
											parts.push({
												is_link:true,
												title:next,
												page:next
											})
										}
									
									}

								}
								return {
									previous:{
										page:paginate.current == 1?'javascript:;':paginate.current - 1
									},
									current_page:paginate.current,
									parts:parts,
									pages:paginate.pageTotal,
									next:{
										page:paginate.current == paginate.pageTotal?'javascript:;':paginate.current + 1
									}
								}
							}
              engine.parseAndRender($("#collection-paginate-temp").html(), {
                paginate: changePaginate(resData.paginate),
                lang: lang
              }).then(function(paginateHTml) {
                $("#collection-product-warp").append(paginateHTml)
                window.productSize && window.productSize( $("#collection-product-warp").find(".product_img"))

                {% if theme_config.global.product_img_list_type != 0 %}
                  let productDetail = new omesaasProduct({})
                  productDetail.renderProductImgList()
                  productDetail = null
                {% endif %}
                $("#collection-product-warp").find(".mo-pagination-value").click(function(){
                  var page = $(this).data("page");
									if(page != 'javascript:;'){
              			$("html,body").stop().animate({ scrollTop: $(".promotion_detail_nav").offset().top }, 400, "linear");
										getCollectionProduct(getParam(page))
									}
                })
                $("#collection-product-warp").find(".mo-pagination-handle").click(function(){
                  var page = $(this).data("page");
									if(page != 'javascript:;'){
              			$("html,body").stop().animate({ scrollTop: $(".promotion_detail_nav").offset().top }, 400, "linear");
										getCollectionProduct(getParam(page))
									}
                })

                
              });
            });
          }else{
            $(".product_num span").text(0)
            $("#collection-product-warp").html($("#collection-product-empty-temp").html())
          }

        }
      })
    }

		$('#sort_by_select').change(function(){
			getCollectionProduct(getParam(1))
		})

		getCollectionProduct(getParam(1))
	})

  {% comment %} $(document).ready(function() {
    var $element = $('.promotion_detail_nav');
    var originalTop = $element.offset().top;
    $(window).scroll(function() {
      if ($(window).scrollTop() > originalTop) {
        $element.css('position', 'fixed').css('top', '0');
      } else {
        $element.css('position', 'static');
      }
    });


  
  }); {% endcomment %}

</script>
{% schema %}
{
	"tag": "section",
	"class": "promotion_detail",
	"is_global": false,
	"name": {
		"zh_CN": "活动详情",
		"en_US": "Promotion detail"
	},
	"max_blocks": 80,
	"settings": [
		{
			"type": "card_header",
			"label": {
				"zh_CN": "设置",
				"en_US": "Settings"
			}
		},
		{
			"type": "card_switch",
			"label": {
				"zh_CN": "是否显示排序",
				"en_US": "Whether to show sorting"
			},
			"default": true,
			"id": "show_sort"
		},
		{
			"type": "card_input_number",
			"max": 80,
			"min": 8,
			"id": "pagesize",
			"label": {
				"zh_CN": "商品每页数量",
				"en_US": "Product number each page"
			},
			"info": {
				"zh_CN": "默认数量12个;最小8个、最大80个;",
				"en_US": "Default number 12, minimum 8, maximum 80;"
			},
			"default": 12
		},
    {
			"type": "card_slider",
			"id": "web_column",
			"max": "6",
			"min": "3",
			"label": {
				"zh_CN": "pc每排商品数量",
				"en_US": "PC number per row"
			}
		}
	],
	"blocks": [],
	"default": {
		"settings": {
			"pagesize": 12,
			"show_sort": true,
      "web_column":4
		},
		"blocks": []
	}
}
{% endschema %}